package com.yhd.task.dynamic;

import cn.hutool.core.collection.CollectionUtil;
import com.yhd.task.model.Task;
import com.yhd.task.model.TaskVO;
import com.yhd.task.service.TaskService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 服务启动扫描数据库获取所有的任务交给spring容器管理
 *
 * @author yinhuidong3@xiaomi.com
 * @since 2021/7/4
 */
@Component
public class StartAll implements CommandLineRunner {

    @Resource
    private TaskService taskService;
    @Resource
    private DynamicCreateTask dynamicCreateTask;
    @Override
    public void run(String... args) throws Exception {
        List<Task> tasks = taskService.listAll();
        if (CollectionUtil.isNotEmpty(tasks)){
            tasks.forEach(t->dynamicCreateTask.createTask(toVo(t)));
        }
        System.out.println("加载完成...");
    }

    private TaskVO toVo(Task task){
        TaskVO vo = new TaskVO();
        vo.setCron(task.getCron());
        vo.setTaskName(task.getTaskName());
        vo.setDescription(task.getDescription());
        vo.setPath(task.getPath());
        vo.setLockAtLeastForString(task.getLockAtLeastForString());
        vo.setLockAtMostForString(task.getLockAtMostForString());
        vo.setLockName(task.getLockName());
        vo.setBeanName(task.getBeanName());
        vo.setClassName(task.getClassName());
        return vo;
    }
}
